<template>
	<view class="page">
		<view class="header-line">互成一家</view>
		<scroll-view class="main-content" scroll-y="true" @scrolltolower="loadMore()">
			<view class="header">
				<view class="header-name">动态</view>
				<view class="header-actions">
					<view class="btn" @click="openAddDynamic">
						<view class="icon" :style="`--icon: url(${ base_url }/static/img/dongtai.svg)`"></view>
						<view class="text">发动态</view>
					</view>
				</view>
			</view>
			<view class="dynamics">
				<view class="dy-list">
					<CirclePostItem
					    v-for="item in dyList"
						:key="item.id"
						:id="String(item.id)"
						:username="item.username"
						:userIcon="item.userIcon"
						:title="item.title"
						:content="item.content"
						:imgList="item.imgList"
						:circlePostType="item.circlePostType"
						:circlePostTypeTextColor="item.circlePostTypeTextColor"
						:circlePostTypeBgColor="item.circlePostTypeBgColor"
						:commentCount="parseInt(item.commentCount)"
                        :likeCount="parseInt(item.likeCount)"
						:isLike="Boolean(item.isLike)"
						:time="item.time"
						@clickLikeBtn="clickLikeBtn"
					/>
				</view>
			</view>
			<view class="addDynamic-shadow" v-show="addDynamicDom.isshow">
				<view class="addDynamic">
					<view class="dialog-header">
						<view class="dialog-title">发动态</view>
					</view>
					<view class="dialog-content">
						<view class="create-help-form">
							<view class="form-group">
								<view class="group-title">标题</view>
								<input type="text" maxlength="30" v-model="addDynamicDom.title">
								<view class="input-count">{{addDynamicDom.title.length}}/30</view>
							</view>
							<view class="form-group">
								<view class="group-title">详细说明</view>
								<textarea v-model="addDynamicDom.content" placeholder="详细描述你的动态内容" rows="4" maxlength="10000"></textarea>
								<view class="input-count">{{addDynamicDom.content.length}}/10000</view>
							</view>
							<view class="form-group">
								<view class="group-title">标签</view>
								<view class="tags-select">
									<view class="tag" :class="item.active ? 'active' : ''" v-for="item in addDynamicDom.tagList" :key="item.id" @click="selectTag(item)">{{ item.text }}</view>
								</view>
							</view>
							<view class="form-row">
								<view class="form-group">
									<view class="group-title">图片</view>
									<view class="photo-list">
										<view class="photo" v-for="item in addDynamicDom.selectedImagesBase64" :key="index" :style="'--bg: url(' + item + ')'">
											<view class="del-photo-btn"></view>
										</view>
										<view class="upload-file" @click="selectImage" v-if="addDynamicDom.selectedImagesBase64.length < 9"></view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="dialog-footer">
						<view class="dialog-btn cancel" @click="closeAddDynamic">取消</view>
						<view class="dialog-btn confirm" @click="addCirclePost">确定</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
// 工具函数
import { formatTime } from '../../util/tool.js';

// 服务层
import { circlePost } from '../../server/circlePost.js';
import { base_url } from '../../server/config';

// 业务层
import { getRecommendPostList } from '../../service/dynamic.js';
import { getCirclePostImgUrl } from '../../service/file.js';

// 组件
import { CirclePostItem } from '../../components/common/CirclePostItem.vue';

export default {
	data() {
		return {
			base_url,
			dyList: [
				// {
				// 	id: 1,
				// 	userIcon: '',
				// 	username: '小明',
				// 	title: '考研互助小组',
				// 	content: '有没有准备考研的同学，一起组队互相监督呀~ 我准备考浙大计算机，最近在刷数学，找个一起学习的伙伴。每天打卡，互相分享学习进度和心得，一起进步！如果你也在准备考研，或者有相关经验，欢迎加入我们~',
                //  imgList: 'xxx',      -- 由 imgIdList 字段计算而来
				// 	circlePostType: '学习',
				//  circlePostTypeTextColor: '',
				//  circlePostTypeBgColor: '',
				// 	commentCount: 5,
				// 	likeCount: 12,
				// 	time: '10分钟前',     -- 由 publishTime 字段计算而来
				//  isLiked: false
				// }
			],
			addDynamicDom: {
				isshow: false,
				tagList: [],
				title: '',
				content: '',
				imgIdList: [],
				selectedImagesBase64: []
			}
		}
	},
	methods: {
		navigateToNextPage(url) {
			uni.navigateTo({ url });
		},
		selectTag(tag) {
			this.addDynamicDom.tagList.forEach(item => {
				let itemId = tag.id;
				if (itemId == item.id) {
					// 设置选中样式
					item.active = !item.active;
				} else {
					item.active = false;
				}
			});
		},
		closeAddDynamic() {
			this.addDynamicDom.title = '';
			this.addDynamicDom.content = '';
			this.addDynamicDom.imgIdList = [];
			this.addDynamicDom.selectedImagesBase64 = [];
			this.addDynamicDom.isshow = false;
		},
		openAddDynamic() {
			this.addDynamicDom.isshow = true;
		},
		loadMore() {
			let lastId = this.dyList[this.dyList.length - 1].id;
			console.log('滑动到了页面底部', lastId);
			getRecommendPostList(this, lastId);
		},
		async addCirclePost() {
			let title = this.addDynamicDom.title;
			let content = this.addDynamicDom.content;
			let publishTime = formatTime(new Date());
			let circlePostTypeId = null;
			if (!title) {
				uni.showToast({
					title: '标题不能为空',
					icon: 'none'
				});
				return ;
			}
			if (!content) {
				uni.showToast({
					title: '内容不能为空',
					icon: 'none'
				});
				return ;
			}
			// 开启加载框ing
			uni.showLoading({
				title: '发布中 请勿关闭窗口 ...'
			});
			// 获取 tagId
			for (let i = 0; i < this.addDynamicDom.tagList.length; i++) {
				let item = this.addDynamicDom.tagList[i];
				if (item.active) {
					circlePostTypeId = item.id;
					break;
				}
			}
			// 预发布动态
			let circlePostId;
			try {
				let res = await circlePost.preAddCirclePost(title, publishTime, content, circlePostTypeId);
                if (res.success) {
					uni.showToast({
						title: '发布成功',
						icon: 'none'
					});
					circlePostId = res.circlePostId;
				} else {
					uni.showToast({
						title: '发布失败',
						icon: 'none'
					});
					return ;
				}
			} catch (err) {
				uni.showToast({
					title: '发布失败',
					icon: 'none'
				});
				return ;
			}
			// 一张张上传图片
			for (let i = 0; i < this.addDynamicDom.selectedImagesBase64.length; i++) {
				let item = this.addDynamicDom.selectedImagesBase64[i];
				try {
					let res = await circlePost.uploadCirclePostImg(item, circlePostId, i);
					if (!res.success) {
						uni.showToast({
							title: '发布失败',
							icon: 'none'
						});
						return ;
					}
				} catch (err) {
					uni.showToast({
						title: '发布失败',
						icon: 'none'
					});
					return ;
				}
			}
			// 确认发布动态
			let res = await circlePost.addCirclePost(circlePostId);
			if (res.success) {
				uni.showToast({
					title: '发布成功',
					icon: 'none'
				});
				// 检查过关之后关闭该窗口
				this.closeAddDynamic();
				
			} else {
				uni.showToast({
					title: '发布失败',
					icon: 'none'
				});
			}
			// 再次刷新帖子列表
			getRecommendPostList(this);
			return ;
		},
		selectImage() {
			let imgCount = this.addDynamicDom.selectedImagesBase64.length;
			imgCount = 9 - imgCount;
			if (!imgCount) {
				uni.showToast({
					title: '最多只能选择9张图片',
					icon: 'none',
					duration: 500
				});
				return ;
			}
			uni.chooseImage({
				count: imgCount,                            // 默认 9
				sizeType: ['original', 'compressed'],       // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'],            // 可以指定来源是相册还是相机，默认二者都有
				success: (res) => {
					// 读取图片并转换为 base64编码的 dataURL并 显示在页面中
					const tempFilePaths = res.tempFilePaths;
					tempFilePaths.forEach((filePath, index) => {
						uni.getFileSystemManager().readFile({
							filePath: filePath,
							encoding: 'base64',
							success: async (res) => {
								const base64Image = `data:image/jpeg;base64,${res.data}`;
								// let imgId = await circlePost.uploadCirclePostImg(base64Image);
								// if (imgId && imgId.success) {
								// 	imgId = imgId.data;
								// }
								// this.addDynamicDom.selectedImagesBase64.push({ id: imgId, img: base64Image });
								// this.addDynamicDom.imgIdList.push(imgId);
								this.addDynamicDom.selectedImagesBase64.push(base64Image);
							},
							fail: (err) => {
								console.error('读取文件失败', err);
							}
						});
					});
				},
				fail: (err) => {
					console.error('选择图片失败', err);
				}
			});
		},
		delSelectedImg(img) {
			let idx = -1;
			for (let i = 0; i < this.addDynamicDom.selectedImagesBase64.length; i++) {
				if (this.addDynamicDom.selectedImagesBase64[i].id == img.id) {
					idx = i;
					break;
				}
			}
		},
		getImgUrl(imgId) {
			return getCirclePostImgUrl(imgId);
		},
		clickLikeBtn(v) {
			console.log('接到通知', v);
			let dyList = this.dyList;
			for (let i = 0; i < dyList.length; i++) {
				if (dyList[i].id == v.id) {
					dyList[i].isLike = v.isLike;
					if (v.isLike) {
						dyList[i].likeCount++;
					} else {
						dyList[i].likeCount--;
					}
					break;
				}
			}
		}
	},
	onLoad() {
		// getRecommendPostList(this); // 获取推荐帖子
		getAllCirclePostType(this);    // 加载所有动态类型
	},
	onShow() {
		getRecommendPostList(this);    // 获取推荐帖子

	},
	components: {
		CirclePostItem
	},
}

function getAllCirclePostType(self) {
	circlePost.getAllCirclePostType().then((res) => {
		if (res.success) {
			self.addDynamicDom.tagList = res.data;
		} else {
			uni.showToast({
				title: '请检查网络',
				icon: 'none'
			});
			// setTimeout(() => {
			// 	getAllCirclePostType(self);
			// }, 500);
		}
	}).catch((err) => {
		uni.showToast({
			title: '请检查网络',
			icon: 'none'
		});
		// setTimeout(() => {
		// 	getAllCirclePostType(self);
		// }, 500);
	});
}

</script>

<style>
.main-content {
	position: relative;
	background-color: #f5f5f5;
	padding: 0;
}

/* 隐藏滚动条 */
::-webkit-scrollbar {
	display: none;
	/* 隐藏滚动条 */
	width: 0;
	/* 设置滚动条宽度为0 */
	height: 0;
	/* 设置滚动条高度为0 */
	color: transparent;
	/* 设置滚动条颜色为透明 */
}

.header {
	width: 100%;
	height: 17vmin;
	box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
	padding: 4vmin 9vmin;
    background-color: #fff;
	box-shadow: 0 -5vmin 0 5vmin #fff;
}

.header .header-name {
    font-size: 4.5vmin;
    font-weight: 600;
}

.header .header-actions {
    display: flex;
    gap: 2vmin;
}

.header .btn {
    display: flex;
    align-items: center;
    gap: 1vmin;
    padding: 1.5vmin 3vmin;
    border-radius: 4.5vmin;
    background: #07c160;
    color: #fff;
    border: none;
    font-size: 3.5vmin;
}

.header .icon {
	width: 6vmin;
	height: 6vmin;
	background-image: var(--icon);
}

.header .text {
	font-size: 3.5vmin;
}

/* 互助动态区域 */
.dynamics {
	padding: 0 5vmin;
	padding-bottom: 20vmin;
	position: relative;
}

.dynamics::after {
	content: "已经到底拉~";
	display: block;
	position: absolute;
	left: 50%;
	bottom: 5vmin;
	transform: translateX(-50%);
	font-size: 3vmin;
}

.addDynamic-shadow {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: #8888;
}

.addDynamic-shadow .addDynamic {
	position: absolute;
	top: 50%;
	left: 50%;
	width: 90vmin;
	height: 75vh;
	transform: translate(-50%, -50%);
	background-color: #fff;
	border-radius: 3vmin;
	display: flex;
	flex-direction: column;
    overflow: hidden;
}

.addDynamic-shadow .dialog-header {
	display: flex;
	padding: 5vmin;
	border-bottom: 0.1vmin solid #ccc;
}

.addDynamic-shadow .dialog-title {
	font-size: 4vmin;
}

.addDynamic-shadow .dialog-content {
	box-sizing: border-box;
	width: 100%;
	flex: 1;
	padding: 5vmin;
	overflow-y: auto;
}

.addDynamic-shadow .form-group {
    margin-bottom: 5vmin;
}

.addDynamic-shadow .form-row {
	display: grid;
	grid-template-columns: 1fr;
	gap: 3vmin;
}

.addDynamic-shadow .group-title {
	display: block;
    margin-bottom: 2vmin;
    color: #333;
    font-size: 3.5vmin;
	font-weight: 900;
}

.addDynamic-shadow input,
.addDynamic-shadow textarea {
	box-sizing: border-box;
    width: 100%;
    padding: 2vmin 3vmin;
    border: 0.25vmin solid #ddd;
    border-radius: 2vmin;
    font-size: 3.5vmin;
    color: #333;
    background: #fff;
}

.addDynamic-shadow input {
	height: 10vmin;
}

.addDynamic-shadow textarea {
    height: 40vmin;
}

.addDynamic-shadow .input-count {
	display: block;
    text-align: right;
    margin-top: 1vmin;
    font-size: 3vmin;
    color: #999;
}

.addDynamic-shadow .tags-select {
    display: flex;
    flex-wrap: wrap;
    gap: 2vmin;
}

.addDynamic-shadow .tag {
    padding: 1.5vmin 3vmin;
    border-radius: 4vmin;
    background: #f5f5f5;
    color: #666;
    font-size: 3.5vmin;
    transition: all .2s;
}

.addDynamic-shadow .tag.active {
	background: #07c160;
    color: #fff;
}

.addDynamic-shadow .upload-file {
	--size: 25vmin;
	width: var(--size);
	height: var(--size);
	border: 0.25vmin solid #ddd;
	border-radius: 1vmin;
	position: relative;
}

.addDynamic-shadow .upload-file::before,
.addDynamic-shadow .upload-file::after {
	content: "";
	display: block;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	background-color: #ddd;
}

.addDynamic-shadow .upload-file::before {
	width: 0.25vmin;
	height: 10vmin;
}

.addDynamic-shadow .upload-file::after {
	width: 10vmin;
	height: 0.25vmin;
}

.addDynamic-shadow .photo-list {
	display: flex;
	gap: 1vmin;
	flex-wrap: wrap;
}

.addDynamic-shadow .form-group .photo {
	width: 25vmin;
	height: 25vmin;
	background-image: var(--bg);
	background-position: center;
	background-repeat: no-repeat;
	background-size: cover;
	position: relative;
}

.addDynamic-shadow .del-photo-btn {
	position: absolute;
	top: 0;
	right: 0;
	width: 7vmin;
	height: 7vmin;
	background-color: rgb(255, 107, 107);
}

.addDynamic-shadow .del-photo-btn::before,
.addDynamic-shadow .del-photo-btn::after {
	content: "";
	display: block;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%) rotate(45deg);
	background-color: #ddd;
}

.addDynamic-shadow .del-photo-btn::before {
	width: 0.5vmin;
	height: 6vmin;
}

.addDynamic-shadow .del-photo-btn::after {
	width: 6vmin;
	height: 0.5vmin;
}

.addDynamic-shadow .dialog-footer {
    display: flex;
    gap: 3vmin;
    padding: 4vmin 5vmin;
    border-top: 0.25vmin solid #f0f0f0;
}

.addDynamic-shadow .dialog-btn {
    flex: 1;
    padding: 2vmin 0;
    border-radius: 5vmin;
    font-size: 3.5vmin;
    font-weight: 500;
    border: none;
	text-align: center;
}

.addDynamic-shadow .dialog-btn.confirm {
	background: #07c160;
	color: #fff;
}

.addDynamic-shadow .dialog-btn.cancel {
    background: #f5f5f5;
    color: #666;
}

</style>



<!-- // {
// 	id: 1,
// 	text: '树洞',
// 	active: false
// }, {
// 	id: 2,
// 	text: '捞人',
// 	active: false
// }, {
// 	id: 3,
// 	text: '表白',
// 	active: false
// }, {
// 	id: 4,
// 	text: '吐槽',
// 	active: false
// }, {
// 	id: 5,
// 	text: '二手',
// 	active: false
// }, {
// 	id: 6,
// 	text: '好物',
// 	active: false
// }, {
// 	id: 7,
// 	text: '避雷',
// 	active: false
// }, {
// 	id: 8,
// 	text: '搭子',
// 	active: false
// }, {
// 	id: 9,
// 	text: '询问',
// 	active: false
// }, {
// 	id: 10,
// 	text: '求助',
// 	active: false
// }, {
// 	id: 11,
// 	text: '工作',
// 	active: false
// }, {
// 	id: 12,
// 	text: '学习',
// 	active: false
// }, {
// 	id: 13,
// 	text: '生活',
// 	active: false
// }, {
// 	id: 14,
// 	text: '趣事',
// 	active: false
// }, {
// 	id: 15,
// 	text: '吃瓜',
// 	active: false
// } -->